
var http = require('../../../../service/http.js');//请求类
var util = require('../../../../utils/util.js');//工具类
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    //-------------所有分类+ 页面加载参数------------------------------------------
    categoryList: ['全部', '超值团购', '乐园门票', '主题活动', '亲子演出', '亲子摄影', '课程体验', '亲子酒店'],
    activeIndex: 0,//被选中得类别
    showCatyAnimationData: '',//展示所有分类动画
    showShareInfo: 0,//是否展示分享信息
    isAuthorization: false,//是否授权登陆
    //----用户登录-----------
    showLogin: false,//是否展示登录
    animationData:'',//登录动画
    isshow: false,//是否显示mask
    opMask: 0,//mask透明度
    toBuy: false,//是否是立即购买
    baseUrl:'../../home/',
    showLoadding: true,//加载动画gif
 
    //---商品相关---------------------------------------------------
    products: [],//所有商品
    product: {},//商品
    minPrice: 0,//最小价格（初始化商品价格范围）
    maxPrice: 0,//最大价格
    skuTitles: [],//sku中title
    isActive: false,//是否被选中
    skus: [],//所有sku内容
    distAttrs: [],
    chooseAttrids: [],//已选属性id
    //----------暂存购物车商品信息-------------------
    itemId: '',//暂存购物车商品id 
    skuId: '',//skuid
    count: 1,//购物车数量
    stock: 0,  //默认库存
    //---------列表分页信息-------------------------
    total:0,//分页总数
    pageNo:1,//分页数
    //---------最大利润最小利润-----------------------
    minFxFee:'',//最小利润
    maxFxFee:'',//最大利润

    shopuid: '',//店铺id
    shopName: '',//店铺名称
    isOwnShop: '',//是否是自己有分销店铺

    itemName:'',//模糊查询商品名称
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
    console.log(options);
    let shopInfo = wx.getStorageSync('shopInfo');
    this.setData({
      shopuid: shopInfo.shopuid || ''
    })
    wx.hideShareMenu();//隐藏转发菜单

    if (options){//获取类别下标
      let showShareInfo = options.showShareInfo;//是否展示分享信息
      let catyindex = options.catyindex;
      console.log('catyindex=' + catyindex + 'showShareInfo=' + showShareInfo);
      this.setData({
        activeIndex: catyindex || 0,
        showShareInfo: showShareInfo ||''
      })
    }
    //全部商品更多分类请求
    console.log('更多分类onLoadjs');
    let [products, itemTypeId, activeIndex] = [[], '', this.data.activeIndex];
    console.log('itemTypeId=' + itemTypeId);
    //获取商品列表-------------------------------------------------------
    let pageNo = this.data.pageNo;//分页页数
    let itemName = this.data.itemName;//商品名称
    this.searchByActiveIndex(pageNo, itemName, activeIndex);
  },
  onShow:function(){
    if (app.data.shopInfoTimeOut === true) { //非分享且已经过期，清除店铺信息
      console.log('店铺信息已过期，重新加载 app.checkSession()');
      app.checkSession();
    }
  },
  onReady: function () {
    let isAuthorization = app.data.isAuthorization;//用户是否已经登录
    console.log('是否已经授权登录+' + isAuthorization);
    this.setData({
      isAuthorization: isAuthorization
    });
  },
  //-----------------查找分类商品=---------------------------------------
  searchByActiveIndex: function (pageNo, itemName, activeIndex){

    //获取店铺信息
    let shopInfo = wx.getStorageSync('shopInfo') || {};
    let shopuid = shopInfo.shopuid || '';
    let itemTypeId = '';
    if (activeIndex == 0) {//等于0分类为全部
      itemTypeId = '';
    } else {
      itemTypeId = '00' + activeIndex;
    }

    http.getReq('/weixin/item/itemList', {
      itemName:itemName,
      pageNo: pageNo,
      pageSize: app.data.pageSize,
      itemTypeId: itemTypeId,
      shopuid: shopuid,//用于根据店铺id查找该店铺上架的商品
      cityName: app.data.cityName || '北京',//获取地理位置
    }, (res)=> {
      // 数据加载成功 停止下拉刷新
      let products = res.data
      let total = res.total//分页总数
    
      this.setData({
        products: products,
        pageNo: pageNo,
        total: total,
        showLoadding: false,
        itemName: itemName
      })
      wx.stopPullDownRefresh();
    });
  },
 
  //-------登陆动画-------------------
  loginAnimation: function () {
    app.loginAnimation();
    this.setData({
      isAuthorization: app.data.isAuthorization,
      animationData: app.data.animationData,
      showLogin: app.data.showLogin
    })
    console.log('showLogin:' + showLogin);
  },
  //-------关闭登陆动画--------------
  closeLoginAnimation: function (e) {
    console.log(e);
    app.closeLoginAnimation(e);
    this.setData({
      animationData: app.data.animationData,
      isAuthorization: app.data.isAuthorization,
      showLogin: app.data.showLogin,
    })
  },

  //---------------------------操作购物车---------------------------------------
  selectValue: function (e) {//点击选择商品属性
    app.selectValue(e);
    this.setData({
      distAttrs: app.data.distAttrs,
      chooseAttrids: app.data.chooseAttrids,
      itemId: app.data.itemId,
      skuId: app.data.skuId,
      stock: app.data.stock,
      count: app.data.count,
      minPrice: app.data.minPrice,
      maxPrice: app.data.maxPrice,
    })
  },
  changeCount: function (e) {//改变数量
    app.changeCount(e, this);
    this.setData({
      count: app.data.count,
      stock: app.data.stock
    })
  },
  minsCount: function (e) {//减少数量
    app.minsCount(e, this);
    this.setData({
      count: app.data.count,
      stock: app.data.stock
    })
  },
  addCount: function (e) {//增加数量
    app.addCount(e, this);
    this.setData({
      count: app.data.count,
      stock: app.data.stock
    })
  },
  addmessage: function (e) {//选择商品信息
    //获取父节点高度----
    wx.createSelectorQuery().select('.page').fields({
      dataset: true,
      size: true,
      scrollOffset: true,
      properties: ['scrollX', 'scrollY']
    },(res)=> {
        // 节点的高度
        this.setData({
          maskHeight: res.height //设置mask高度
        })
      }).exec()
    //获取父节点高度--------------------------------------
    console.log(e)
    app.addmessage(e, this);//调用全局方法
    setTimeout( ()=> {
      console.log('延时赋值');
      this.setData({
        animationData: app.data.animationData,//加入购物车动画
        toBuy: app.data.toBuy,
        isshow: app.data.isshow,
        product: app.globalData.product,
        minPrice: app.data.minPrice,
        maxPrice: app.data.maxPrice,
        skus: app.data.skus,
        skuTitles: app.data.skuTitles,
        distAttrs: app.data.distAttrs,
        stock: app.data.stock,
        chooseAttrids: app.data.chooseAttrids
      })
    }, 500)

    // console.log(app.data.product);
  },
  unAddMessage: function (e) {//关闭
    app.unAddMessage(e, this);
    setTimeout(()=> {
      this.setData({
        animationData: app.data.animationData,//加入购物车动画
        toBuy: app.data.toBuy,
        isshow: app.data.isshow,
        skus: app.data.skus,
        distAttrs: app.data.distAttrs,
        chooseAttrids: app.data.chooseAttrids,
        itemId: app.data.itemId,
        skuId: app.data.skuId,
        count: app.data.count,
        stock: app.data.stock,
      })
      console.log('itemId--' + app.data.itemId);
      console.log('skuId--' + app.data.skuId);
      console.log('count--' + app.data.count);
      console.log('stock--' + app.data.stock);
    }, 200)


  },


  selectProductById: function (e) {//根据商品id 查商品详情
    console.log('根据商品id 查商品详情参数', e);
    this.setData({
      productId: e.currentTarget.dataset.productid,
      pageUrl: '/pages/product/product'
    })
    util.throttle(app.selectProductById, 500, this);
  },

  onPullDownRefresh: function () {//下拉刷新 加载全部商品
    console.log("下拉刷新");
    let products = [];
    //加载动画
    this.setData({
      showLoadding: true
    })
    //获取商品列表-------------------------------------------------------
    let [activeIndex, pageNo] = [this.data.activeIndex,1];

    let itemName = this.data.itemName;
    this.searchByActiveIndex(pageNo, itemName, activeIndex);
  },
  //展示所有分类
  showCatyBody:function(){
    this.setData({
      showCaty: true,
    })
  },
  //隐藏所有分类
  hideCatyBody:function(){
    this.setData({
      showCaty: false,
    })
  },
  //根据分类查找商品
  searchCategoryList:function(e){
    let activeIndex = e.currentTarget.dataset.actindex;
    this.setData({
      showCaty: false, //隐藏分类列表
      activeIndex: activeIndex,
      showLoadding: true
    })
    let [pageNo, itemName] = [1, this.data.itemName];

    //根据activeIndex \itemName查找商品分类
    this.searchByActiveIndex(pageNo, itemName, activeIndex);
  },
  //加载更多
  onReachBottom: function (e) {
    let [pageNo, total, activeIndex] = [this.data.pageNo, this.data.total, this.data.activeIndex];
    //获取店铺信息
    let shopInfo = wx.getStorageSync('shopInfo');
    let shopuid = shopInfo.shopuid || '';
    let itemName = this.data.itemName;
    let [products, setProList, pageSize, itemTypeId] = [[], [], app.data.pageSize, ''];//加载分页的商品列表（用于局部刷新）
    if (pageNo < total) {
      //隐藏加载动画
      this.setData({
        showLoadding: true
      })
      pageNo = pageNo + 1;
      if (activeIndex != 0) {
        itemTypeId = '00' + activeIndex;
      }
      http.getReq('/weixin/item/itemList', {
        itemName: itemName,
        pageNo: pageNo,
        pageSize: pageSize,
        itemTypeId: itemTypeId,
        shopuid: shopuid,//用于根据店铺id查找该店铺上架的商品
        cityName: app.data.cityName || '北京',//获取地理位置
      }, (res)=> {
        let newList = res.data;
        if (pageNo > 1) {
          products = this.data.products;//原商品列表
        
          for (let item of newList ){
            setProList[`products[${products.length}]`] = item;
            products.length++;
          }
          
          this.setData({
            ...setProList
          })

        } else {//第一次加载商品
          products.push(...newList);
          this.setData({
            products: products
          })
        }
        // console.log('products', products);
       
        this.setData({
          pageNo: pageNo,
          showLoadding: false,
          itemName:itemName
        })
      });
     
    }
  },
  //------------------未开通服务提示----------------------
  unOpen: function () {
    app.unOpen();
  },
  onShareAppMessage: function (options){//分享该商品
    let [products, index] = [this.data.products, options.target.dataset.index];
    console.log('转发途径:')
    console.log(options);
    let product = products[index];
    let [shareTitle, inviter, shareImg, shopuid, shopInfo] = [product.itemName, wx.getStorageSync('unionid'), product.itemimags[0].imgs, '',wx.getStorageSync('shopInfo')]//商品id 和 推荐人uid
    
    if (shopInfo.shopuid){
      shopuid = shopInfo.shopuid;
    }
    console.log("分享人id" + inviter);
    console.log("productId--" + product.id + 'inviter----' + inviter + "shopuid:---" + shopuid);
    return {
      title: shareTitle,
      imageUrl: shareImg,
      path: '/pages/product/product?parms=' + product.id + '/' + inviter + '/' + shopuid + '/0'
    }
  },
  //商品列表缩略图 图片加载失败出现错误时替换图片路径
  errImg: function (e) {
    console.log(e);
    let proIndex = e.currentTarget.dataset.proindex;//商品下标
    let [products, hotPorducts] = [[], []];
    let isSellHot = e.currentTarget.dataset.isSellHot;//是否是热销列表

    if (isSellHot == '1') {//热销列表
      hotPorducts = this.data.hotPorducts;
      this.setData({
        hotPorducts: app.errImg(hotPorducts, proIndex)//返回products 更改thumbImgs路径
      })
    } else {//普通商品列表
      products = this.data.products;
      this.setData({
        products: app.errImg(products, proIndex)//返回products 更改thumbImgs路径
      })
    }
  },
  getFormId: function (e) {
    app.getFormId(e);
  },
  
  //根据商品名称差商品列表
  selectListByItemName:function(e){
    console.log('根据商品名称差商品列表',e);
    let itemName = e.detail.value.itemName || '';
    if (e.type == 'confirm') {//触发键盘按钮触发
      itemName = e.detail.value;
    }
    let pageNo = 1;
    let activeIndex = this.data.activeIndex;//类别
    this.searchByActiveIndex(pageNo, itemName, activeIndex)
  }

})